package top.xana.acg.anime.ui.view

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.core.view.isInvisible
import androidx.navigation.findNavController
import top.xana.acg.anime.R
import top.xana.acg.anime.utils.ToastUtils

/**
 * Created by xana on 2022/1/15
 * Describe: hello world
 */
class SearchView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) :
    FrameLayout(context, attributeSet, defStyleAttr, defStyleRes), View.OnClickListener {

    private val back: ImageView
    private val inputView: EditText
    private val delView: ImageView

    public var kw: String = ""

    init {
        LayoutInflater.from(context).inflate(R.layout.view_search_view, this)
        back = findViewById(R.id.back)
        inputView = findViewById(R.id.inputView)
        delView = findViewById(R.id.delete)
        /*  inputView.setOnEditorActionListener { view, actionId, event ->
            kw = view.text.toString()
            if ((event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                searchListener?.onSearch(kw!!)
                true;
            }
            false
        }
        */

        inputView.setOnEditorActionListener { _, i, _ ->
            if (i == EditorInfo.IME_ACTION_SEARCH && kw.isNotEmpty()) {
                searchPtr?.let { it(kw) }
                ToastUtils.showShort("搜索: $kw")
                inputView.clearFocus()
            }
            false
        }
        inputView.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                kw = p0.toString()
//                if (p0?.endsWith('\n') == true) {
////                    hintKb(App.app(), inputView)
//                    searchPtr?.let { it(kw) }
//                    //  inputView.setText("")
//                }
                delView.isInvisible = p0?.length == 0
            }

            override fun afterTextChanged(p0: Editable?) {}
        })
        delView.setOnClickListener(this)
        back.setOnClickListener(this)
    }

    private var searchPtr: ((String) -> Unit)? = null
    fun setSearchPtr(searchPtr: ((String) -> Unit)?) {
        this.searchPtr = searchPtr
    }

    override fun onClick(v: View?) {
        if (v == delView) {
            inputView.setText(R.string.empty)
        } else if (v == back) {
            findNavController().navigateUp()
        }
    }
}